
<template>
  <div>
    <div class="gva-search-box" style="padding: 16px; border-radius: 4px; margin-bottom: 16px;">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="姓名">
          <el-input v-model="searchInfo.memberName" placeholder="请输入姓名" clearable style="width: 180px;" />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="searchInfo.phone" placeholder="请输入手机号" clearable style="width: 180px;" />
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchInfo.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 250px;"
          />
        </el-form-item>

        <el-form-item label="余额范围">
          <el-select v-model="searchInfo.balanceRange" placeholder="全部" style="width: 120px;">
            <el-option label="全部" value="all" />
            <el-option label="0-1000" value="0-1000" />
            <el-option label="1000-5000" value="1000-5000" />
            <el-option label="5000-10000" value="5000-10000" />
            <el-option label="10000以上" value="10000+" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="onReset">重置</el-button>
          <el-button type="primary" @click="onSubmit" style="margin-left: 10px;">应用筛选</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div style="display: flex; justify-content: flex-end; margin-bottom: 16px;">
        <el-button type="primary" icon="plus" @click="openDialog()">新增会员</el-button>
      </div>
      <el-table
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="id"
      >
        <el-table-column align="left" label="姓名" prop="memberName">
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <el-avatar :src="scope.row.avatar || '/src/assets/noBody.png'" size="small" style="margin-right: 8px;" />
              {{ scope.row.memberName }}
            </div>
          </template>
        </el-table-column>


        <el-table-column align="left" label="手机号" prop="phone" />

        <el-table-column align="left" label="会员等级" prop="memberLevel">
          <template #default="scope">{{ formatMemberLevel(scope.row.memberLevel) }}</template>
        </el-table-column>

        <el-table-column align="left" label="余额(元)" prop="balance">
          <template #default="scope">
              {{ scope.row.balance.toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column align="left" label="时间" prop="registrationDate">
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>

        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="text" @click="openRechargeDialog(scope.row)" style="color: #67c23a;">
              <el-icon><Money /></el-icon>
              充值
            </el-button>
            <el-button type="text" @click="openConsumptionDialog(scope.row)" style="color: #f56c6c;">
              <el-icon><ShoppingCart /></el-icon>
              扣费
            </el-button>
            <el-button type="text" @click="viewRechargeRecords(scope.row)" style="color: #409eff;">
              <el-icon><Document /></el-icon>
              记录
            </el-button>
            <el-button type="text" @click="updateMembersFunc(scope.row)" style="color: #409eff;">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="text" @click="deleteRow(scope.row)" style="color: #f56c6c;">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination" style="margin-top: 16px;">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
       <template #header>
              <div class="flex justify-between items-center">
                <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
                <div>
                  <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
                  <el-button @click="closeDialog">取 消</el-button>
                </div>
              </div>
            </template>

          <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
            <el-form-item label="会员姓名:" prop="memberName">
    <el-input v-model="formData.memberName" :clearable="true" placeholder="请输入会员姓名" />
</el-form-item>
            <el-form-item label="手机号:" prop="phone">
    <el-input v-model="formData.phone" :clearable="true" placeholder="请输入手机号" />
</el-form-item>
            <el-form-item label="会员等级:" prop="memberLevel">
    <el-select v-model="formData.memberLevel" placeholder="请选择会员等级" clearable >
      <template v-if="memberLevels.length > 0">
        <el-option v-for="level in memberLevels" :key="level.levelCode" :label="level.levelName" :value="level.levelCode" />
      </template>
      <template v-else>
        <el-option label="普通会员" :value="1" />
        <el-option label="银卡会员" :value="2" />
        <el-option label="金卡会员" :value="3" />
        <el-option label="钻石会员" :value="4" />
      </template>
    </el-select>
</el-form-item>

            <el-form-item label="状态:" prop="status">
    <el-select v-model="formData.status" placeholder="请选择状态" clearable >
      <el-option label="正常" :value="1" />
      <el-option label="停用" :value="2" />
    </el-select>
</el-form-item>
            <el-form-item label="备注信息:" prop="remark">
    <el-input v-model="formData.remark" :clearable="true" placeholder="请输入备注信息" />
</el-form-item>
          </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
            <el-descriptions :column="1" border>
                    <el-descriptions-item label="会员姓名">
    {{ detailForm.memberName }}
</el-descriptions-item>
                    <el-descriptions-item label="手机号">
    {{ detailForm.phone }}
</el-descriptions-item>
                    <el-descriptions-item label="会员等级">
    {{ formatMemberLevel(detailForm.memberLevel) }}
</el-descriptions-item>
                    <el-descriptions-item label="账户余额">
    {{ detailForm.balance }}
</el-descriptions-item>
                    <el-descriptions-item label="累计充值金额">
    {{ detailForm.totalRecharge }}
</el-descriptions-item>
                    <el-descriptions-item label="累计消费金额">
    {{ detailForm.totalConsumption }}
</el-descriptions-item>
                    <el-descriptions-item label="注册时间">
    {{ detailForm.registrationDate }}
</el-descriptions-item>
                    <el-descriptions-item label="状态">
    {{ formatStatus(detailForm.status) }}
</el-descriptions-item>
                    <el-descriptions-item label="备注信息">
    {{ detailForm.remark }}
</el-descriptions-item>
            </el-descriptions>
        </el-drawer>

    <!-- 充值弹窗 -->
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="rechargeDialogVisible" :show-close="false" :before-close="closeRechargeDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">会员充值 - {{ rechargeForm.memberName }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="confirmRecharge">确认充值</el-button>
            <el-button @click="closeRechargeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <div class="recharge-form">
        <el-alert
          :title="'当前余额：¥' + rechargeForm.currentBalance.toFixed(2)"
          type="info"
          :closable="false"
          class="balance-alert"
        />
        
        <el-form-item label="会员等级" prop="memberLevel">
          <div class="member-level-info">
            {{ formatMemberLevel(rechargeForm.memberLevel) }}
          </div>
        </el-form-item>

        <el-form :model="rechargeForm" label-position="top" label-width="120px">
          <el-form-item label="充值金额 (元)" required>
            <el-input-number
              v-model="rechargeForm.rechargeAmount"
              :min="0"
              :step="100"
              :precision="2"
              style="width: 100%;"
              placeholder="请输入充值金额"
              @change="calculateGift"
            />
            <div class="recharge-tips">
              <template v-if="memberLevels.length > 0">
                充值优惠：
                <template v-for="level in memberLevels.sort((a, b) => b.levelCode - a.levelCode)" :key="level.levelCode">
                  {{ level.levelName }}({{ level.levelCode }}级){{ level.rechargeGiftRate > 0 ? `送${level.rechargeGiftRate}%` : '不赠送' }}
                  <template v-if="!$last">，</template>
                </template>
              </template>
              <template v-else>
                充值优惠：钻石会员(4级)送20%，金卡会员(3级)送15%，银卡会员(2级)送10%，普通会员(1级)不赠送
              </template>
            </div>
          </el-form-item>

          <el-form-item label="赠送金额 (元)" v-if="rechargeForm.giftAmount > 0">
            <el-input-number
              v-model="rechargeForm.giftAmount"
              :disabled="true"
              :precision="2"
              style="width: 100%;"
              class="gift-amount"
            />
          </el-form-item>

          <el-form-item label="到账金额 (元)">
            <div class="recharge-amount">
              ¥{{ (rechargeForm.rechargeAmount + rechargeForm.giftAmount).toFixed(2) }}
            </div>
          </el-form-item>

          <el-form-item label="支付方式">
            <el-select v-model="rechargeForm.paymentMethod" style="width: 100%;">
              <el-option
                v-for="method in paymentMethods"
                :key="method.value"
                :label="method.label"
                :value="method.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="rechargeForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <!-- 消费弹窗 -->
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="consumptionDialogVisible" :show-close="false" :before-close="closeConsumptionDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">会员消费 - {{ consumptionForm.memberName }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="confirmConsumption">确认扣费</el-button>
            <el-button @click="closeConsumptionDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <div class="consumption-form">
        <el-alert
          :title="'当前余额：¥' + consumptionForm.currentBalance.toFixed(2)"
          type="info"
          :closable="false"
          class="balance-alert"
        />
        <el-form-item label="消费项目" required>
            <el-select v-model="consumptionForm.projectType" style="width: 100%;" @change="onProjectTypeChange">
              <el-option
                v-for="project in projectTypes"
                :key="project.value"
                :label="project.label"
                :value="project.value"
              />
            </el-select>
          </el-form-item>
        <el-form :model="consumptionForm" label-position="top" label-width="120px">
          <el-form-item label="消费金额 (元)" required>
            <el-input-number
              v-model="consumptionForm.consumptionAmount"
              :min="0"
              :step="10"
              :precision="2"
              style="width: 100%;"
              placeholder="请输入消费金额"
              @change="calculateFinalAmount"
            />
            <div class="consumption-tips">
              消费后余额：¥{{ calculateRemainingBalance().toFixed(2) }}
            </div>
          </el-form-item>

          <el-form-item label="会员等级" prop="memberLevel">
            <div class="member-level-info">
              {{ formatMemberLevel(consumptionForm.memberLevel) }}
            </div>
          </el-form-item>

          <el-form-item label="当前折扣" prop="discountRate">
            <div class="discount-info">
              {{ (consumptionForm.discountRate * 10).toFixed(1) }}折
            </div>
          </el-form-item>

          <el-form-item label="实际扣费金额" prop="finalAmount">
            <div class="final-amount-info">
              ¥{{ consumptionForm.finalAmount.toFixed(2) }}
            </div>
          </el-form-item>

          

          <el-form-item label="项目名称" v-if="consumptionForm.projectType === 4">
            <el-input
              v-model="consumptionForm.projectName"
              placeholder="请输入产品名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="consumptionForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  createMembers,
  deleteMembers,
  deleteMembersByIds,
  updateMembers,
  findMembers,
  getMembersList,
  rechargeMember,
  consumeMember
} from '@/api/hairmember/members'
import { getMemberLevelsPublic } from '@/api/hairmember/memberLevels'
import { getProjectTypesPublic } from '@/api/hairmember/projectTypes'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict ,filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from "@/pinia"
import { emitter } from '@/utils/bus'
import { Edit, InfoFilled, Delete, Money, Document, ShoppingCart } from '@element-plus/icons-vue'




defineOptions({
    name: 'Members'
})

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()
const router = useRouter()
// 操作类型变量（create/create）
const type = ref('')

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
            id: undefined,
            memberName: '',
            phone: '',
            memberLevel: 1,
            status: 1,
            remark: '',
        })



// 验证规则
const rule = reactive({
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========// 表格控制部分
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
// 会员等级数据
const memberLevels = ref([])
// 项目类型数据
const projectTypes = ref([])
// 项目名称映射（用于快速查找）
const projectNamesMap = ref({})
// 项目价格映射（用于快速查找）
const projectPricesMap = ref({})
const searchInfo = ref({
  memberName: '',
  phone: '',
  timeRange: [],
  balanceRange: 'all'
})
// 重置
const onReset = () => {
  searchInfo.value = {
    memberName: '',
    phone: '',
    timeRange: [],
    balanceRange: 'all'
  }
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  }
  params.timeRange = null
  // 如果有时间范围，处理时间参数
  if (searchInfo.value.timeRange && searchInfo.value.timeRange.length === 2) {
    params.startDate = searchInfo.value.timeRange[0]
    params.endDate = searchInfo.value.timeRange[1]
  } else {
    params.startDate = ''
    params.endDate = ''
  }
  const table = await getMembersList(params)
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

// ============== 表格控制部分结束 ===============

// 获取项目类型数据
const getProjectTypesData = async () => {
  try {
    const res = await getProjectTypesPublic()
    if (res.code === 0 && res.data && res.data.length > 0) {
      // 转换数据格式为el-select组件所需的格式
      projectTypes.value = res.data.map(item => ({
        value: item.typeCode,
        label: item.typeName
      }))
      
      // 构建项目名称映射表
      const projectNames = {}
      // 构建项目价格映射表
      const projectPrices = {}
      
      res.data.forEach(item => {
        projectNames[item.typeCode] = item.typeName
        // 从后端获取项目价格，如果没有价格字段则使用默认值
        projectPrices[item.typeCode] = item.price || 0
      })
      projectNamesMap.value = projectNames
      projectPricesMap.value = projectPrices
    } else {
      // 降级策略：如果后端没有返回数据，使用默认值
      projectTypes.value = [
      ]
      projectNamesMap.value = {
        1: '理发服务',
        2: '烫染服务',
        3: '护理服务'
      }
      // 设置默认价格映射
      projectPricesMap.value = {
        1: 38,  // 理发默认价格
        2: 168, // 烫染默认价格
        3: 88   // 护理默认价格
      }
    }
  } catch (error) {
    console.error('获取项目类型数据失败:', error)
    // 降级策略：请求失败时使用默认值
    projectTypes.value = [
      { value: 1, label: '理发' },
      { value: 2, label: '烫染' },
      { value: 3, label: '护理' },
      { value: 4, label: '产品' }
    ]
    projectNamesMap.value = {
      1: '理发服务',
      2: '烫染服务',
      3: '护理服务'
    }
    // 设置默认价格映射
    projectPricesMap.value = {
      1: 38,  // 理发默认价格
      2: 168, // 烫染默认价格
      3: 88   // 护理默认价格
    }
  }
}

// 获取会员等级数据
const setMemberLevels = async () => {
  try {
    const res = await getMemberLevelsPublic()
    if (res.code === 0) {
      // 只显示启用状态(1)的会员等级
      memberLevels.value = (res.data || []).filter(level => level.status === 1)
    } else {
      ElMessage.error('获取会员等级失败')
    }
  } catch (error) {
    ElMessage.error('获取会员等级失败')
  }
}

// 状态格式化
const formatStatus = (status) => {
  return status === 1 ? '正常' : '停用'
}

// 初始化数据
const initData = async () => {
  await getTableData()
  await setMemberLevels()
  await getProjectTypesData()
}

initData()

// 监听会员等级更新事件，自动刷新会员等级数据
const handleMemberLevelsUpdated = async () => {
  await setMemberLevels()
}

// 监听项目类型更新事件，自动刷新项目类型数据
const handleProjectTypesUpdated = async () => {
  await getProjectTypesData()
}

// 注册事件监听
emitter.on('memberLevelsUpdated', handleMemberLevelsUpdated)
emitter.on('projectTypesUpdated', handleProjectTypesUpdated)

// 组件卸载时移除事件监听
onUnmounted(() => {
  emitter.off('memberLevelsUpdated', handleMemberLevelsUpdated)
  emitter.off('projectTypesUpdated', handleProjectTypesUpdated)
})

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteMembersFunc(row)
        })
    }

// 多选删除功能暂时移除，如果需要可以重新添加

// 更新会员信息
const updateMembersFunc = async (row) => {
    type.value = 'update'
    const res = await findMembers({ id: row.id })
    if (res.code === 0) {
        formData.value = res.data
        dialogFormVisible.value = true
    }
}

// 删除行
const deleteMembersFunc = async (row) => {
    const res = await deleteMembers({ id: row.id })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 充值弹窗控制
const rechargeDialogVisible = ref(false)
const rechargeForm = ref({
  memberId: undefined,
  memberName: '',
  currentBalance: 0,
  rechargeAmount: 0,
  giftAmount: 0,
  paymentMethod: 1,
  remark: ''
})

// 消费弹窗控制
const consumptionDialogVisible = ref(false)
const consumptionForm = ref({
  memberId: undefined,
  memberName: '',
  currentBalance: 0,
  memberLevel: 1,
  discountRate: 1,
  consumptionAmount: 0,
  finalAmount: 0,
  projectType: 1,
  projectName: '',
  remark: ''
})

// 支付方式选项
const paymentMethods = [
  { label: '现金', value: 1 },
  { label: '微信支付', value: 2 },
  { label: '支付宝', value: 3 },
  { label: '银行卡', value: 4 }
]

// 格式化会员等级
const formatMemberLevel = (level) => {
  if (memberLevels.value && memberLevels.value.length > 0) {
    const levelItem = memberLevels.value.find(item => item.levelCode === level)
    return levelItem ? levelItem.levelName : '普通会员'
  }
  // 降级策略：如果没有从后端获取到数据，使用默认值
  const defaultLevelNames = {
    1: '普通会员',
    2: '银卡会员',
    3: '金卡会员',
    4: '钻石会员'
  }
  return defaultLevelNames[level] || '普通会员'
}

// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        id: undefined,
        memberName: '',
        phone: '',
        memberLevel: 1,
        status: 1,
        remark: '',
    }
}
// 弹窗确定
const enterDialog = async () => {
     btnLoading.value = true
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return btnLoading.value = false
              let res
              switch (type.value) {
                case 'create':
                  res = await createMembers(formData.value)
                  break
                case 'update':
                  res = await updateMembers(formData.value)
                  break
                default:
                  res = await createMembers(formData.value)
                  break
              }
              btnLoading.value = false
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

const detailForm = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findMembers({ id: row.id })
  if (res.code === 0) {
    detailForm.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailForm.value = {}
}

// 打开充值弹窗
const openRechargeDialog = (row) => {
  rechargeForm.value = {
    memberId: row.id,
    memberName: row.memberName,
    currentBalance: row.balance,
    memberLevel: row.memberLevel, // 添加会员等级字段
    rechargeAmount: 0,
    giftAmount: 0,
    paymentMethod: 1,
    remark: ''
  }
  rechargeDialogVisible.value = true
}

// 打开消费弹窗
const openConsumptionDialog = (row) => {
  // 根据会员等级设置折扣率
  let discountRate = 1
  if (memberLevels.value && memberLevels.value.length > 0) {
    const levelItem = memberLevels.value.find(item => item.levelCode === row.memberLevel)
    if (levelItem && levelItem.consumeDiscountRate) {
      discountRate = levelItem.consumeDiscountRate / 100
    }
  } else {
    // 降级策略：如果没有从后端获取到数据，使用默认值
    switch (row.memberLevel) {
      case 2: // 银卡会员
        discountRate = 0.95
        break
      case 3: // 金卡会员
        discountRate = 0.9
        break
      case 4: // 钻石会员
        discountRate = 0.85
        break
      default: // 普通会员
        discountRate = 1
    }
  }
  
  consumptionForm.value = {
    memberId: row.id,
    memberName: row.memberName,
    currentBalance: row.balance,
    memberLevel: row.memberLevel,
    discountRate: discountRate,
    // 从价格映射表中获取初始项目类型对应的价格，默认为0
    consumptionAmount: projectPricesMap.value[1] || 0,
    finalAmount: 0,
    projectType: 1,
    projectName: projectNamesMap.value[1] || '理发服务',
    remark: ''
  }
  
  // 确保项目类型数据已加载
  if (projectTypes.value.length === 0) {
    getProjectTypesData()
  }
  
  // 计算初始的实际扣费金额
  calculateFinalAmount()
  
  consumptionDialogVisible.value = true
}

// 关闭充值弹窗
const closeRechargeDialog = () => {
  rechargeDialogVisible.value = false
  rechargeForm.value = {
    memberId: undefined,
    memberName: '',
    currentBalance: 0,
    memberLevel: 1, // 默认普通会员
    rechargeAmount: 0,
    giftAmount: 0,
    paymentMethod: 1,
    remark: ''
  }
}

// 关闭消费弹窗
const closeConsumptionDialog = () => {
  consumptionDialogVisible.value = false
  consumptionForm.value = {
    memberId: undefined,
    memberName: '',
    currentBalance: 0,
    memberLevel: 1,
    discountRate: 1,
    consumptionAmount: 0,
    finalAmount: 0,
    projectType: 1,
    projectName: '',
    remark: ''
  }
}

// 查看充值记录
const viewRechargeRecords = (row) => {
  // 跳转到充值记录页面，传递会员ID
  router.push({
    name: 'RechargeRecords',
    query: { memberId: row.id, memberName: row.memberName }
  })
}

// 计算赠送金额
const calculateGift = () => {
  const rechargeAmount = rechargeForm.value.rechargeAmount
  const memberLevel = rechargeForm.value.memberLevel
  let giftAmount = 0
  
  if (memberLevels.value && memberLevels.value.length > 0) {
    const levelItem = memberLevels.value.find(item => item.levelCode === memberLevel)
    if (levelItem && levelItem.rechargeGiftRate) {
      giftAmount = rechargeAmount * levelItem.rechargeGiftRate
    }
  } else {
    // 降级策略：如果没有从后端获取到数据，使用默认值
    switch (memberLevel) {
      case 4: // 钻石会员
        giftAmount = rechargeAmount * 0.2
        break
      case 3: // 金卡会员
        giftAmount = rechargeAmount * 0.15
        break
      case 2: // 银卡会员
        giftAmount = rechargeAmount * 0.1
        break
      default: // 普通会员及其他
        giftAmount = 0
    }
  }
  
  rechargeForm.value.giftAmount = giftAmount
}

// 项目类型变化处理
const onProjectTypeChange = () => {
  // 项目价格映射表
  // 当选择产品类型时，清空项目名称和金额
  if (consumptionForm.value.projectType === 4) {
    consumptionForm.value.projectName = ''
    consumptionForm.value.consumptionAmount = 0
  } else {
    // 使用从后端获取的项目名称
    consumptionForm.value.projectName = projectNamesMap.value[consumptionForm.value.projectType] || ''
    // 自动填充对应项目的默认价格
    consumptionForm.value.consumptionAmount = projectPricesMap.value[consumptionForm.value.projectType] || 0
  }
  
  // 重新计算实际扣费金额
  calculateFinalAmount()
}

// 确认充值
const confirmRecharge = async () => {
  if (!rechargeForm.value.rechargeAmount || rechargeForm.value.rechargeAmount < 10) {
    ElMessage.error('充值金额必须大于等于10元')
    return
  }

  btnLoading.value = true
  try {
    // 使用后端要求的接口格式 - 注意字段名是memberId而不是memberID
    const res = await rechargeMember({
      memberId: rechargeForm.value.memberId,
      rechargeAmount: rechargeForm.value.rechargeAmount,
      paymentMethod: rechargeForm.value.paymentMethod,
      remark: rechargeForm.value.remark
    })

    if (res.code === 0) {
      ElMessage.success('充值成功')
      closeRechargeDialog()
      getTableData()
    } else {
      ElMessage.error(res.msg || '充值失败')
    }
  } catch (error) {
    ElMessage.error('充值请求失败')
  } finally {
    btnLoading.value = false
  }
}

// 计算实际扣费金额
const calculateFinalAmount = () => {
  if (typeof consumptionForm.value.consumptionAmount === 'number' && typeof consumptionForm.value.discountRate === 'number') {
    consumptionForm.value.finalAmount = consumptionForm.value.consumptionAmount * consumptionForm.value.discountRate
  } else {
    consumptionForm.value.finalAmount = 0
  }
}

// 计算消费后余额
const calculateRemainingBalance = () => {
  const currentBalance = typeof consumptionForm.value.currentBalance === 'number' ? consumptionForm.value.currentBalance : 0
  const finalAmount = typeof consumptionForm.value.finalAmount === 'number' ? consumptionForm.value.finalAmount : 0
  return currentBalance - finalAmount
}

// 确认消费
const confirmConsumption = async () => {
  if (!consumptionForm.value.consumptionAmount || consumptionForm.value.consumptionAmount <= 0) {
    ElMessage.error('消费金额必须大于0')
    return
  }

  if (consumptionForm.value.finalAmount > consumptionForm.value.currentBalance) {
    ElMessage.error('实际扣费金额不能大于当前余额')
    return
  }

  btnLoading.value = true
  try {
    const res = await consumeMember({
      memberId: consumptionForm.value.memberId,
      consumptionAmount: consumptionForm.value.consumptionAmount,
      finalAmount: consumptionForm.value.finalAmount,
      discountRate: consumptionForm.value.discountRate,
      projectType: consumptionForm.value.projectType,
      projectName: consumptionForm.value.projectName,
      remark: consumptionForm.value.remark
    })

    if (res.code === 0) {
      ElMessage.success('扣费成功')
      closeConsumptionDialog()
      getTableData()
    } else {
      ElMessage.error(res.msg || '扣费失败')
    }
  } catch (error) {
    ElMessage.error('扣费请求失败')
  } finally {
    btnLoading.value = false
  }
}


</script>

<style scoped>
.gva-search-box {
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.recharge-amount {
  font-size: 24px;
  color: #67c23a;
  font-weight: bold;
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  margin: 10px 0;
}

.gift-amount {
  color: #e6a23c;
  font-weight: bold;
}

.balance-alert {
  margin-bottom: 20px;
}

.recharge-form {
  padding: 20px;
}

.recharge-tips {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  line-height: 1.5;
}

.consumption-form {
  padding: 20px;
}

.consumption-tips {
  color: #67c23a;
  font-size: 14px;
  margin-top: 8px;
  font-weight: bold;
}

.member-level-info {
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
  padding: 8px;
  background-color: #f0f9ff;
  border-radius: 4px;
  display: inline-block;
}

.discount-info {
  font-size: 18px;
  color: #e6a23c;
  font-weight: bold;
  padding: 8px;
  background-color: #fdf6ec;
  border-radius: 4px;
  display: inline-block;
}

.final-amount-info {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
  padding: 8px;
  background-color: #fef0f0;
  border-radius: 4px;
  display: inline-block;
}
</style>
